const { no, ok } = require('../../utils/utlis');
const userService = require('../../services/admin/userService');
const JWT = require('../../utils/jwt');

module.exports = {
	// 登录
	login: async (req, res, next) => {
		try {
			let { mobile, password } = req.body;
			if (!mobile) return no('手机号不能为空！');
			if (!password) return no('密码不能为空！');

			//   数据库
			let token = await userService.login(mobile, password);
			res.send(ok({ token }));
		} catch (error) {
			res.send(no(error.message));
		}
	},
	// 用户信息
	userInfo: async (req, res, next) => {
		try {
			let { id } = JWT.decrypt(req.headers.token);
			let obj = await userService.userInfo(id);
			obj.routes = obj.routes.split(',');
			res.send(ok(obj));
		} catch (error) {
			res.send(no(error.message));
		}
	},
	// 用户列表
	list: async (req, res, next) => {
		try {
			let { pageNum, pageSize, keywords, type } = req.body;
			if (!pageNum || !pageSize) return res.send(no('参数错误'));
			let data = await userService.list(pageNum, pageSize, keywords, type);
			res.send(ok(data));
		} catch (error) {
			res.send(no(error.message));
		}
	},
	// 新增
	add: async (req, res, next) => {
		try {
			let { username, mobile, roleId, password } = req.body;
			await userService.add(username, mobile, roleId, password);
			res.send(ok());
		} catch (error) {
			res.send(no(error.message));
		}
	},
	// 编辑
	edit: async (req, res, next) => {
		try {
			let { username, mobile, roleId, password, id } = req.body;
			await userService.edit(username, mobile, roleId, password, id);
			res.send(ok());
		} catch (error) {
			res.send(no(error.message));
		}
	},
	// 详情
	detail: async (req, res, next) => {
		try {
			let { id } = req.body;
			if (!id) return res.send(no('未传用户id'));
			let obj = await userService.detail(id);
			res.send(ok(obj));
		} catch (error) {
			res.send(no(error.message));
		}
	},
	// 退出登录
	layout: async () => {
		return ok();
	},
	del: async (req, res, next) => {
		try {
			let { id } = req.body;
			if (!id) return res.send(no('未传用户id'));
			await userService.del(id);
			res.send(ok());
		} catch (error) {
			res.send(no(error.message));
		}
	},
	// 博主
	setBloger: async (req, res, next) => {
		try {
			let { content } = req.body;
			await userService.setBloger(content);
			res.send(ok());
		} catch (error) {
			res.send(no(error.message));
		}
	},
	getBloger: async (req, res, next) => {
		try {
			let obj = await userService.getBloger(res);
			res.send(ok(obj));
		} catch (error) {
			res.send(no(error.message));
		}
	}
};
